import md5 from 'js-md5'
import { IAuthInfo } from '~/types/sys/IAuthInfo'
import http from '~/utils/axios'

class LoginService {
  private urls = {
    login: '/login/check',
    logout: '/login/logout',
    info: '/login/info'
  }

  async login(userName: string, password: string): Promise<string | IAuthInfo> {
    return new Promise<string | IAuthInfo>((resolve, reject) => {
      http
        .post<IAuthInfo>(this.urls.login, {
          userName: userName,
          password: md5(password)
        })
        .then(
          (response) => {
            if (response.success == false) {
              resolve(<string>response.message)
            }
            resolve(response.data)
          },
          (response) => {
            //针对于登录，成功和失败都要进行处理
            if (response.success == false) {
              resolve(<string>response.message)
            }
            resolve(response.data)
          }
        )
    })
  }

  async logout() {
    await http.post(this.urls.logout)
  }

  async info(): Promise<IAuthInfo> {
    return new Promise<IAuthInfo>((resolve) => {
      http.post<IAuthInfo>(this.urls.info).then((response) => {
        resolve(response.data)
      })
    })
  }
}

export default new LoginService()
